import axios from 'axios';
import server from './serve';
import qs from 'qs';
import {
  Toast
} from 'mint-ui';
import {
  MessageBox
} from 'mint-ui';
import Vue from 'vue'

axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

const appJS = {
  userInfo:{//测试账号
    
  },
  config:{
    os:1,
    version:2
  },
  // 数据请求
  ajax(url, method = "get", data = {}, callback,vm) {  
    if(vm){
      vm.bus.$emit('loading', true);
    }
    data.token = this.getStorage('userInfo').token
    data.os = this.config.os
    data.version = this.config.version
    if (method == 'get') {
      var visual_url = '?'
      for (var i in data) {
        visual_url += i + '=' + data[i] + '&'
      }
    } else {
      var visual_url = ''
    }
    axios({
      method: method,
      url: server[url] + visual_url,
      data: qs.stringify(data)
    }).then(res => {
      if (res) {
        if(vm){
          setTimeout(()=>{
            vm.bus.$emit('loading', false);
          },200)
        }
        if(data.data=='1'){
          callback(res)
        }else{
          callback(res.data)
        }
        if (res.data.recode != 1) {
          if(data.mask=='none'){}else{
            Toast({
              message: res.data.msg,
              position: 'middle',
              duration: 2000
            })
          }
          
        }
        return
      }
    }).catch(res => { //接口请求失败
      if(vm){
        setTimeout(()=>{
          vm.bus.$emit('loading', false);
        },200)
      }
      console.log("接口请求失败")
      Toast({
        message: '数据请求失败...',
        position: 'bottom',
        duration: 2000
      });
    })
  },
  // 获取缓存信息
  getStorage(key, types = 0) {
    //0=>json对象   other=>字符串
    if (localStorage.getItem(key)) { //存在该缓存
      if (types == 0) {
        return JSON.parse(localStorage.getItem(key))
      } else {
        return localStorage.getItem(key)
      }
    } else {
      return false
    }
  },
  // 设置缓存
  setStorage(key, data, types = 0) {
    //0=>json对象   other=>字符串
    if (types == 0) {
      localStorage.setItem(key, JSON.stringify(data))
    } else {
      localStorage.setItem(key, data)
    }
  },
  // 清除缓存
  clearStorage(key, types = 0) {
    //0=>清除单个   other=>清除所有缓存信息
    if (types == 0) {
      localStorage.removeItem(key)
    } else {
      localStorage.clear()
    }
  }
}

export default appJS
